import 'dart:ffi';
import 'dart:io';

import 'package:fluent_ui/fluent_ui.dart' hide Colors;
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pie_menu/pie_menu.dart';
import 'package:tools/src/rust/api/api.dart' as api;
import 'package:tools/src/rust/api/screen_util.dart';
import 'package:tools/src/rust/api/simple.dart';
import 'package:tools/src/rust/frb_generated.dart';
import 'package:tools/src/utils/copy_exe_to_local.dart';
import 'package:tools/src/utils/flutter_util.dart';
import 'package:tools/src/view/home/home_page.dart';
import 'package:tools/src/view/screen_hot/screen_hot_page.dart';
import 'package:win32/win32.dart';
import 'package:desktop_multi_window/desktop_multi_window.dart';
import 'dart:convert';


int? findWindowByTitle(String title) {
  final ptr = TEXT(title);
  final hwnd = FindWindow(nullptr, ptr);
  free(ptr);
  if (hwnd == 0) return null;
  return hwnd;
}


void setWindowRect({int left = 100, int top = 100, int width = 300, int height = 300}) async {
  //print("setWindowRect: left=$left, top=$top, width=$width, height=$height");
  // 获取主窗口 HWND
  
  final int? hwnd = await NativeWindowApi.getMainWindowHandle();
  // 设置窗口大小和位置
  SetWindowPos(
    hwnd!,
    HWND_TOPMOST,
    left,
    top,
    width,
    height,
    SWP_NOACTIVATE,
  );
}

void showWindowRect({bool show = false}) async {
  // 获取主窗口 HWND
  final int? hwnd = await NativeWindowApi.getMainWindowHandle();
  // 设置窗口大小和位置
  if (show) {
    ShowWindow(hwnd!, SW_SHOW);
  } else {
    ShowWindow(hwnd!, SW_HIDE);
  }
    
}

bool open = false;
//传递可以变值 类型
//final screenShotNotifier = ValueNotifier<bool>(false);
//final clipboardNotifier = ValueNotifier<bool>(false);

String screen_hot_path = "";


Future<void> main(List<String> args) async {
  await RustLib.init();
  final dir = await getApplicationSupportDirectory();
  screen_hot_path = '${dir.path}/plugins/r_screen_shot/r_screen_shot.exe';
  addPath(exePath: screen_hot_path);

  print("args: $args");
  if (args.firstOrNull == 'multi_window') {
    final Map<String, dynamic> point = jsonDecode(args[2]);
    if (point["args1"].toString() == "home_page") {
      runApp(FluentApp(
        theme: FluentThemeData(
          visualDensity: VisualDensity.standard,
        ),
        home: HomePage(),
      ));
    } else if (point["args1"].toString() == "screen_hot_page") {
      
      runApp(FluentApp(
        theme: FluentThemeData(
          visualDensity: VisualDensity.standard,
        ),
        home: ScreenHotPage(),
      ));
    } else {

    }

  }else{
    // 直接调用 Rust 代码
    api.startListenInput().listen((eventJson) async {
      final Map<String, dynamic> point = jsonDecode(eventJson);
      if(point['state'].toString() == "show"){
        setWindowRect(left: point['x'].toInt() - 150, top: point['y'].toInt() - 150);
        showWindowRect(show: true);
        //模拟点击
        if (!open) {
          api.simulatedMouse(x:point['x'].toInt(), y:point['y'].toInt());
          open = true;
        }
      } else if(point['state'].toString() == "hide"){
        showWindowRect(show: false);
      } else if(point['state'].toString() == "screenshot") {
        final dir = await getApplicationSupportDirectory();
        final exePath = '${dir.path}/plugins/r_screen_shot/r_screen_shot.exe';

        try {
          // 后台启动 exe（不会阻塞 Flutter）
          await Process.start(
            exePath,
            [], // 参数列表，如果 exe 需要参数就在这里传
            mode: ProcessStartMode.detached,
          );
          print('已启动: $exePath');
        } catch (e) {
          print('启动失败: $e');
        }
      }
    });
    
    runApp(MaterialApp(
      home: RadialMenuExample(),
      debugShowCheckedModeBanner: false,
    ));
  }
}

class RadialMenuExample extends StatefulWidget {
  const RadialMenuExample({super.key});

  @override
  State<RadialMenuExample> createState() => _RadialMenuExampleState();
}

class _RadialMenuExampleState extends State<RadialMenuExample> {
  final PieMenuController _controller = PieMenuController();
  bool showButton = true; // 控制圆饼显示

  @override
  void initState() {
    super.initState();
    initializePluginsOnce();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.transparent,
      body: PieCanvas(
        onMenuToggle: (isOpen) {
            // 菜单关闭时显示圆饼，菜单打开时隐藏圆饼
            setState(() {
              open = isOpen;
              print("菜单状态1: $isOpen");
            });
          },
        child: PieMenu(
          controller: _controller,
          theme: PieTheme(
            longPressDuration: const Duration(milliseconds: 10),
            overlayColor: Colors.transparent,
            buttonTheme: PieButtonTheme(
              backgroundColor: Colors.transparent,
              iconColor: Colors.white,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2),
              ),
            ),
          ),
          actions: [
            PieAction(
              tooltip: Text('打开主页'),
              onSelect: () async {
                final window = await DesktopMultiWindow.createWindow(jsonEncode({
                  'args1': 'home_page',
                }));
                await window.setFrame(Rect.fromLTRB(0, 0, 820, 600));
                await window.center();
                await window.setTitle('主页');
                await window.show();
              },
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.blue,
                  shape: BoxShape.circle,
                  border: Border.all(color: Colors.white, width: 2),
                ),
                padding: const EdgeInsets.all(8),
                child: Icon(Icons.home, color: Colors.white),
              ),
            ),
            PieAction(
              tooltip: Text('截图'),
              onSelect: () async  {
                try {
                  // 后台启动 exe（不会阻塞 Flutter）
                  await Process.start(
                    screen_hot_path,
                    [], // 参数列表，如果 exe 需要参数就在这里传
                    mode: ProcessStartMode.detached,
                  );
                  showWindowRect(show: false);
                  print('已启动: $screen_hot_path');
                  
                } catch (e) {
                  print('启动失败: $e');
                }

              },
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.pink,
                  shape: BoxShape.circle,
                  border: Border.all(color: Colors.white, width: 2),
                ),
                padding: const EdgeInsets.all(8),
                child: Icon(Icons.screenshot, color: Colors.white),
              ),
            ),
          ],
          child: Center(
            child: showButton
                ? GestureDetector(
                    onTapDown: (details) {
                     
                    },
                    child: Container(
                      width: 30,
                      height: 30,
                      decoration: BoxDecoration(
                        color: Colors.red,
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white, width: 3),
                      ),
                    ),
                  )
                : const SizedBox.shrink(),
          ),
        ),
      ),
    );
  }
}